//
//  UIImage+Extensions.swift
//  MYModule
//
//  Created by 易先生 on 2022/8/1.
//

import Foundation

extension UIImage{
    
    public func originalImageWithColor(color:UIColor) -> UIImage {
        if #available(iOS 13.0, *) {
            return self.withTintColor(color,renderingMode: .alwaysOriginal)
        } else {
            let img = setupImageTintColor(tintColor: color)
            let image = img.withRenderingMode(.alwaysOriginal)
            return image
        }
    }
    
    public func setupImageTintColor(tintColor :UIColor, blendModels:[CGBlendMode] = [.destinationIn]) -> UIImage {
        
        UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)
        tintColor.setFill()
        let bounds = CGRect.init(x:0, y:0, width:self.size.width, height:self.size.height)
        UIRectFill(bounds)
        blendModels.forEach { blendMode in
            self.draw(in: bounds, blendMode:blendMode, alpha:1.0)
        }
//        self.draw(in: bounds, blendMode:.overlay, alpha:1.0)
        
        let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return tintedImage!
        
    }
    
    /**
     * 通过颜色获取图片
     */
    public static func imageWithColor(_ color:UIColor)->UIImage{
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor)
        context!.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
   public static func image(_ text:String,
                             size:CGSize,
                             backColor:UIColor,
                             textColor:UIColor ,
                             textFont:UIFont,
                             cornerRadius:CGFloat) -> UIImage?{
        if text.isEmpty { return nil }
        let letter = (text as NSString).substring(to: 2)
        let rect = CGRect(origin: CGPoint.zero, size: size)
        UIGraphicsBeginImageContext(size)
        guard let ctx = UIGraphicsGetCurrentContext() else { return nil }
        UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip()
        ctx.setFillColor(backColor.cgColor)
        ctx.fill(rect)
        
        let attr = [NSAttributedString.Key.foregroundColor:textColor,NSAttributedString.Key.font:textFont]
        let textSize = text.size(withAttributes: attr)
        (letter as NSString).draw(at: CGPoint(x: (size.width - textSize.width)*0.5, y: (size.height - textSize.height)*0.5), withAttributes: attr)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}



public extension UIImage {
    
    func reSizeImage(reSize:CGSize,_ scal: CGFloat = UIScreen.main.scale)->UIImage {
        UIGraphicsBeginImageContextWithOptions(reSize,false,UIScreen.main.scale);
        self.draw(in: CGRect(x: 0, y: 0, width: reSize.width, height: reSize.height));
        let reSizeImage = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
        UIGraphicsEndImageContext()
        return reSizeImage;
    }
    
    func pixelData() -> [UInt8]? {
        let size = self.size
        print("size = \(size)")
        let dataSize = size.width * size.height * 4
        var pixelData = [UInt8](repeating: 0, count: Int(dataSize))
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let context = CGContext(data: &pixelData,
                                width: Int(size.width),
                                height: Int(size.height),
                                bitsPerComponent: 8,
                                bytesPerRow: 4 * Int(size.width),
                                space: colorSpace,
                                bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)
        guard let cgImage = self.cgImage else { return nil }
        context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        
        return pixelData
    }
    
}

func saveImage(currentImage: UIImage, persent: CGFloat, imageName: String){
    
    print("saveImage")
    
    if let imageData = currentImage.pngData() as NSData? {
        let imagePath = NSHomeDirectory().appending("/Documents/").appending(imageName)
        imageData.write(toFile: imagePath, atomically: true)
        print("imagePath=\(imagePath),imageSize = \(currentImage.size)")
    }
}

func removeImage(imageName: String){
    let fileManager = FileManager.default
    let imagePath = NSHomeDirectory().appending("/Documents/").appending(imageName)
    do {
        try fileManager.removeItem(atPath: imagePath)
    }catch{
        
    }
}



